package com.PomodoroTimer;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;

import android.net.Uri;
import android.os.*;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.media.*;
import android.media.MediaPlayer.OnErrorListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import java.io.File;
import java.io.IOException;
import java.util.*;


public class Home extends Activity {
	
	Timer _timer;
	MediaPlayer _workPlayer;
	MediaPlayer _restPlayer;

    AudioManager _audioManager;
    Vibrator _vibrator;
	
	
	AppController _controller;
	
	private NotificationManager mNManager;
	private static final int NOTIFY_ID=1100;
	
	com.google.code.microlog4android.Logger logger;
	
	AlertDialog WorkTimeEndedDialog;
	AlertDialog RestTimeEndedDialog;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.PomodoroTimer.R.layout.main);
        _audioManager =  (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        _vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        logger =com.google.code.microlog4android.LoggerFactory.getLogger();
        com.google.code.microlog4android.appender.FileAppender appender = new com.google.code.microlog4android.appender.FileAppender();
        File file = Environment.getExternalStorageDirectory();
        String s = file.getPath();
        file = new File (s+"/l.txt");
        if (!file.exists())
        {
        	
        	try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
        }
        //appender.setFileName(file.getPath());
        //appender.setAppend(true);
        
        logger.addAppender(appender);
        try {
			appender.open();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
        logger.setLevel(com.google.code.microlog4android.Level.DEBUG);
        logger.debug("Started");
        
        
        
        
        _controller = AppController.Instance();
        _controller.setPreferences(getSharedPreferences("settings", Context.MODE_PRIVATE));
        
        if ((savedInstanceState==null)||(!savedInstanceState.containsKey("WorkingTime")))
        {
        	// run at first time
        	workTimerText().setText(_controller.getTime().getWorkTimeText());
            restTimerText().setText(_controller.getTime().getRestTimeText());
            
        	_timer = new Timer(_controller.getTime(),mUpdateTimeTask);
        	
        }
        else
        {
        	PomodoroTime currentTime = new PomodoroTime(savedInstanceState.getLong("WorkingTime"), savedInstanceState.getLong("RestTime"));
        	workTimerText().setText(currentTime.getWorkTimeText());
            restTimerText().setText(currentTime.getRestTimeText());
            
        	_timer = new Timer (currentTime,mUpdateTimeTask);
        	boolean _isTimerStarted = savedInstanceState.getBoolean("IsTimerStarted");
        	if (_isTimerStarted)
        	{
        		_timer.Start();
        		startStopButton().setChecked(true);
        	}
        }
        _controller.setTimer(_timer);
        
        if (_workPlayer==null)
        {
        _workPlayer = new MediaPlayer();
        _workPlayer = MediaPlayer.create(this, R.raw.sound01);
        _workPlayer.setOnErrorListener(new OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				mp.reset();
				return false;
			}
		});
        
        _restPlayer = new MediaPlayer();
       _restPlayer = MediaPlayer.create(this,R.raw.sound02);
        _restPlayer.setOnErrorListener(new OnErrorListener() {
			
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				mp.reset();
				return false;
			}
		});
        }
        startStopButton().setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked)
				{
					_timer.Start();
					ShowNotification("Timer Started");
				}
				else
				{
					_timer.Stop();
					ShowNotification("Timer Stopped");
				}
				
			}
		});
        
        resetButton().setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				_timer.Reset();
				workTimerText().setText(_controller.getTime().getWorkTimeText());
		        restTimerText().setText(_controller.getTime().getRestTimeText());
			}
		});
        InitDialogs();
    }
    
    private void InitDialogs()
    {
    	WorkTimeEndedDialog = new AlertDialog.Builder(this).create();
    	WorkTimeEndedDialog.setMessage(GetStringResource(R.string.WorkTimeEnded)+". Do you want to rest?");
    	WorkTimeEndedDialog.setButton(DialogInterface.BUTTON_POSITIVE,"Rest!",
    			new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						_controller.getTimer().StartRestTimer();
					}
				});
    	WorkTimeEndedDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
    			new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						startStopButton().setChecked(false);
					}
				}
    			);
    	
    	RestTimeEndedDialog= new AlertDialog.Builder(this).create();
    	RestTimeEndedDialog.setMessage(GetStringResource(R.string.RestTimeEnded)+". Do you want to work?");
    	
    	RestTimeEndedDialog.setButton(DialogInterface.BUTTON_POSITIVE,"Work!",
    			new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						_controller.getTimer().StartWorkTimer();
					}
				});
    	RestTimeEndedDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
    			new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						startStopButton().setChecked(false);
					}
				}
    			);
    }
    
    private void ShowNotification (String message)
    {
    	String ns = Context.NOTIFICATION_SERVICE;
    	//if (mNManager!=null)
    	//{
    		mNManager = (NotificationManager)getSystemService(ns);
    	//}
    	Notification msg = new Notification(R.drawable.icon, message, System.currentTimeMillis());
    	
    	Context context = getApplicationContext();
    	Intent msgIntent = new Intent(this,Home.class);
    	msgIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    	msgIntent.setAction("android.intent.action.MAIN");
    	msgIntent.addCategory("android.intent.category.LAUNCHER");
    	PendingIntent intent =	PendingIntent.getActivity(this, 0, msgIntent, 0);
    	//msg.defaults |= Notification.DEFAULT_SOUND;
    	msg.defaults |= Notification.DEFAULT_VIBRATE;
    	//msg.flags |= Notification.FLAG_AUTO_CANCEL;
    	msg.setLatestEventInfo (context,"Pomodor Timer", message, intent);
    	mNManager.notify(NOTIFY_ID, msg);
    }
    
    private String GetStringResource (int id)
    {
    	Resources myResources = getResources();
    	return myResources.getString(id);
    }
    
    
    
    private void ShowWorkTimeEndedAlert ()
    {
    	
    	WorkTimeEndedDialog.show();
    }
    
    private void ShowRestTimeEndedAlert ()
    {
    	
    	RestTimeEndedDialog.show();
    }
    
    private PomodoroTimerEventHandler mUpdateTimeTask = new PomodoroTimerEventHandler() {
    	   
    	   

		@Override
		public void Tick(PomodoroTime time) {
			 String workTime = time.getWorkTimeText();
		     String restTime = time.getRestTimeText();
		     workTimerText().setText(workTime);
		     restTimerText().setText(restTime);
		}

		@Override
		public void WorkTimeEnded() {
            int ringerMode = _audioManager.getRingerMode();
            if (ringerMode== AudioManager.RINGER_MODE_NORMAL)
            {
                int v = _audioManager.getStreamVolume(AudioManager.STREAM_RING);
                _workPlayer.setVolume((float)v,(float)v);
			    _workPlayer.start();

            }
            else if (ringerMode==AudioManager.RINGER_MODE_VIBRATE)
            {
                long[] pattern = {500,1000};
                _vibrator.vibrate(pattern, -1);
            }
            else if (ringerMode==AudioManager.RINGER_MODE_SILENT)
            {
                long[] pattern = {0,500};
                _vibrator.vibrate(pattern, -1);
            }

			ShowNotification(GetStringResource(R.string.WorkTimeEnded));
			ShowWorkTimeEndedAlert();
		}

		@Override
		public void RestTimeEnded() {
            int ringerMode = _audioManager.getRingerMode();
            if (ringerMode== AudioManager.RINGER_MODE_NORMAL)
            {
                int v = _audioManager.getStreamVolume(AudioManager.STREAM_RING);
                _restPlayer.setVolume((float)v,(float)v);
			    _restPlayer.start();
            }
            else if (ringerMode==AudioManager.RINGER_MODE_VIBRATE)
            {
                long[] pattern = {500,1000};
                _vibrator.vibrate(pattern, -1);
            }
            else if (ringerMode==AudioManager.RINGER_MODE_SILENT)
            {
                long[] pattern = {0,500};
                _vibrator.vibrate(pattern, -1);
            }
			ShowNotification(GetStringResource(R.string.RestTimeEnded));
			ShowRestTimeEndedAlert();
		}
		
		@Override
		public void TimeSet(PomodoroTime time)
		{
			workTimerText().setText( time.getWorkTimeText());
		    restTimerText().setText(time.getRestTimeText());
		}

		@Override
		public void TimerReseted(PomodoroTime time) {
			 workTimerText().setText( time.getWorkTimeText());
		     restTimerText().setText(time.getRestTimeText());
			
		}
		
    	};
        
    @Override
    protected void onSaveInstanceState (Bundle outState)
    {
    	outState.putLong("WorkingTime", _timer.getCurrentTime().getWorkTime());
    	outState.putLong("RestTime", _timer.getCurrentTime().getRestTime());
    	outState.putBoolean("IsTimerStarted", _timer.getIsStarted());
    	
    	try {
			logger.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Override
    protected void onRestoreInstanceState (Bundle savedInstanceState)
    {
    	super.onRestoreInstanceState(savedInstanceState);
    	//restore the relevant information
    	
    }
    	
    public TextView workTimerText ()
    {
    	return (TextView)this.findViewById(R.id.WorkTimerText);
    }
    
    public TextView restTimerText ()
    {
    	return (TextView)this.findViewById(R.id.RestTimerText);
    }
    
    public ToggleButton startStopButton ()
    {
    	return (ToggleButton)this.findViewById(R.id.toggleButton1);
    }
    
    public Button resetButton()
    {
    	return (Button)this.findViewById(R.id.resetButton);
    }
    
    
    @Override
    public void onStart ()
    {
    	super.onStart();
    	
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	MenuItem m = menu.findItem(R.id.item1);
    	menu.findItem(R.id.item1).setIntent(new Intent(this,com.PomodoroTimer.SettingsMenu1.class));
    	return true;
}
    
   
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.item1:
        	startActivity(item.getIntent());
        	
            return true;
        
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    
}